import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, Keyboard,
	PixelRatio, TextInput, ScrollView, KeyboardAvoidingView, Platform
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { TitleView } from '../_components/TitleView.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import OrderAPIService from '../_common/OrderAPIService';
import moment from 'moment';
import DateGapPicker from '../../../../components/common/DateGapPicker';
import ToastUtil from '../../../../utils/toast';
import MethodUtil from '../../../../utils/MethodUtil';
const scale = GLOBAL.SCALE;
export class PlanShopping extends Component {
	static navigationOptions = {
		header: null
	}
	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		this.orderId = params.orderId;   // 订单id
		this.goodsList = params.goodsList;   // 商品数据
		this.type = params.type;  // 计划添加完成 返回组建名
		this.type2 = params.type2 || false;
		this.amountData = params.elementAmount || [];
		this.tCode = params.tCode;

		console.log('this.goodsList', this.goodsList);
		console.log('params.editData', params.editData);
		console.log('this.amountData', params.elementAmount);
		// 编辑
		if (params.editData) {
			this.editData = params.editData.map((item) => {
				// 数字转字符quantity
				item.goodsDeliveryPlanList = item.goodsDeliveryPlanList && item.goodsDeliveryPlanList.map((alignItems, index) => {
					alignItems.quantity = alignItems.quantity && alignItems.quantity.toString();
					return alignItems
				});
				return item.goodsDeliveryPlanList;
			})
		}
		let lsArr = this._creactData();
		this.allData = params.editData || [{ deliveryBeginDate: '', deliveryEndDate: '', orderId: this.orderId, goodsDeliveryPlanList: lsArr }];
		this.state = {
			listData: this.allData,
			timeModal: false, // 时间模态框
			deliveryBeginDate: false,  // 开始时间
			deliveryEndDate: false,   // 结束时间
			writeIndex: 0,  // 标记编辑第几个 交货计划
			status: 'data',
			openDatePicker: false,
		}
		this.dateObj = {

		}
	}

	componentWillMount () {
		this._commitCall = this._commitCall.bind(this);
		this._moreQuantity();  //初始余量
	}

	//保存
	async	_commitCall () {
		let onOff = false;
		//控制量
		this.amountData.forEach((item) => {
			if (item.residue < 0) {
				//ToastUtil.showWarning(`${item.goodsName}商品超出总量${Math.abs(item.residue)}吨`);
				onOff = false;
			}
		})
		if (onOff) {
			return false;
		}
		let lsB = this.type2 || 'deliveryPlanList';
		let sendData = {
			submitStep: 'ADD_DELIVERY_PLAN',
			orderInfo: {
				orderId: this.orderId
			},
		}

		sendData[lsB] = this.allData;
		// 过滤空时间
		let newPlanList = this.allData.filter((item) => {
			item.goodsDeliveryPlanList.map(goodsItem => {
				if (!(Number.parseFloat(goodsItem.quantity) > 0)) {
					goodsItem.quantity = '0';
				}
			})
			if (this.tCode === 'L') {
				return item
			} else if (item.deliveryBeginDate != '' && item.deliveryEndDate != '') {
				return item
			}
		})

		console.log(newPlanList, 'newPlanList---------------')
		sendData[lsB] = newPlanList;
		this.setState({
			status: 'loading'
		});

		let saveData = await OrderAPIService.deliveryPlanAdd(sendData)

		this.setState({
			status: 'data'
		})
		if (saveData) {
			ToastUtil.showSuccess('交货计划保存成功').then(() => {
				this.props.navigation.state.params.callBack(saveData);
				this.props.navigation.navigate(this.type);
			})
		}
	}

	//剩余量计算- input 框
	_computer = () => {
		this._moreQuantity();
	}

	// 获取余量
	_geResidue = (index) => {
		let result = 0;
		if (this.allData.length > 0) {
			this.allData.forEach((item) => {
				if (item.goodsDeliveryPlanList[index] && item.goodsDeliveryPlanList[index].quantity) {
					result = MethodUtil.countObj.add(result, Number.parseFloat(item.goodsDeliveryPlanList[index].quantity));
				}
			});
			result = MethodUtil.countObj.subtract(this.amountData[index].amount, result)
			console.log('result1', result)
		} else {
			result = this.amountData[index].amount;
			console.log('result2', result)
		}
		console.log('值', result)
		return result
	}

	// 余量 初始化
	_moreQuantity = () => {
		this.amountData.map((item, index) => {
			item.residue = this._geResidue(index);
			return item;
		})
	}

	//创建数据
	_creactData = () => {
		let lsData = [];
		this.goodsList.forEach((item, index) => {
			let newItem = Object.assign({}, item);
			if (index == 0) {
				lsData.push(newItem);
			}
		})
		let lsArr = [];
		lsData.map((item, index, arr) => {
			if (Number.parseFloat(this.amountData[index].residue) > 0) {
				item.quantity = this.amountData[index].residue + '';
				this.amountData[index].residue = 0;
			} else {
				item.quantity = '0';
			}
			return lsArr.push(Object.assign({}, item));
		})
		return lsArr;
	}

	//添加数据
	_addItem = () => {
		let { listData } = this.state;
		if (listData.length > 0 && this.tCode == 'L') {
			ToastUtil.showWarning('长约合同只有一条交货计划');
			return;
		}
		let newData = this._creactData();
		this.allData.push({
			deliveryBeginDate: '', deliveryEndDate: '', orderId: this.orderId, goodsDeliveryPlanList: newData
		});
		this.setState({
			listData: this.allData
		})
	}

	//清空
	clearAll = async () => {
		let { listData } = this.state;
		let subData = {
			submitStep: 'DELETE_DELIVERY_PLAN',
			deliveryPlan: {
				orderId: this.orderId
			}
		};

		let saveData = await OrderAPIService.deliveryPlanDel(subData);
		this.allData = [];
		//this.amountData = [];
		this._moreQuantity();  //计算
		this.setState({
			listData: this.allData
		});
	}

	//删除某一条
	removeItem = async (index) => {
		let { listData } = this.state;
		let subData = {
			submitStep: 'DELETE_DELIVERY_PLAN',
			deliveryPlan: {
				deliveryBeginDate: listData[index].deliveryBeginDate,
				deliveryEndDate: listData[index].deliveryEndDate,
				orderId: this.orderId
			}
		};
		let saveData = await OrderAPIService.deliveryPlanDel(subData);
		if (!saveData) { return }
		this.amountData.map((goodsItem, goodsIndex) => {
			listData[index].goodsDeliveryPlanList.map((item, index) => {
				if (goodsItem.itemId === item.itemId) {
					let oldNumber = Number.parseFloat(this.amountData[index].residue);
					this.amountData[goodsIndex].residue = MethodUtil.countObj.add(oldNumber, Number.parseFloat(item.quantity || 0));
				}
			})
		})
		listData.splice(index, 1);
		this.setState({
			listData
		})
	}

	// 时间 - 打开时间弹框 以及初始化
	_openInit = (index) => {
		this.setState({
			timeModal: true,
			writeIndex: index,
			deliveryBeginDate: this.allData[index].deliveryBeginDate || false,
			deliveryEndDate: this.allData[index].deliveryEndDate || false,
			endTimeIndex: this.allData[index].endTimeIndex || null,
			startTimeIndex: this.allData[index].startTimeIndex || null,
		})
	}

	//时间 -
	_modelClick = () => {
		this.setState({ timeModal: false })
	}

	//时间 -查找字符串中的数字  并且返回数组
	_getNumberFn = (str) => {
		if (!str) return;
		var numberArr = [];
		var newStr = str.replace(/\d+/g, function () {
			numberArr.push(arguments[0]);
		});
		return numberArr.join('-');
	}

	// 时间  - 选择时间回调
	_setTimeCallback = (obj) => {
		var $index = this.state.writeIndex;
		this.allData[$index].deliveryBeginDate = this._getNumberFn(obj.startTime);
		this.allData[$index].deliveryEndDate = this._getNumberFn(obj.endTime);
		this.allData[$index].startTimeIndex = obj.startTimeIndex;
		this.allData[$index].endTimeIndex = obj.endTimeIndex;
		this.setState({
			listData: this.allData
		})
	}

	openDatePicker = (index, item) => {
		Keyboard.dismiss();
		this.dateObj.startDate = item.deliveryBeginDate || '';
		this.dateObj.endDate = item.deliveryEndDate || '';
		if (this.tCode === 'F') {
			this.dateObj.limitStart = moment().add(20, 'd').format('YYYY-MM-DD')
		}
		this.setState({ writeIndex: index, openDatePicker: true });
	}

	//时间  - 关闭时间弹框
	_closeFn = () => {
		this.setState({ timeModal: false })
	}

	//顶部关闭按钮
	_headCloes = () => {
		this.props.navigation.state.params.callBack();
		this.props.navigation.navigate(this.type);
	}
	render () {
		let { listData, status, } = this.state;
		let imgObj = require('../../../../imgs/arrow-left.png');
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<View style={styles.boxPadding}>
					<Common type="headCloes" callBack={this._headCloes} />
					<TitleView title={'交货计划'} describe={this.tCode === 'L' ? '每月执行' : ''} />
				</View>
				<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'}>
					{/* <View style={[styles.amountBox, styles.boxPadding]}>
						{
							this.amountData.map((item, index) => {
								return (<View key={index} style={styles.goodListBox}>
									<Text style={styles.goodNameTitle}>{item.goodsName} </Text>
									<View style={styles.goodList}>
										<Text style={styles.infoBody}>总量：<Text style={styles.amountStyle}>{item.amount}吨</Text></Text>
										 <Text style={[{ paddingLeft: 15 * scale }, styles.infoBody]}>剩余量：<Text style={styles.amountStyle}>{item.residue}吨</Text></Text> 
									</View>
								</View>)
							})
						}
					</View> */}
					{this.tCode === 'L' ? <Text style={[styles.amountStyle, { paddingLeft: 15 * scale, marginTop: 15 * scale, }]}>具体交货计划请看合同附件文本规定</Text> : null}
					<View style={{ flexDirection: "row" }}>
						<TouchableOpacity onPress={() => { this._addItem() }} style={[styles.addBtn, { marginLeft: 15 * scale }]}>
							<Text style={styles.addBtnText}>添加交货计划</Text>
						</TouchableOpacity>
						<TouchableOpacity onPress={() => { this.clearAll() }} style={[styles.addBtn, { marginLeft: 15 * scale }]}>
							<Text style={styles.addBtnText}>清空</Text>
						</TouchableOpacity>
					</View>
					<View style={styles.planCommon}>
						{
							listData.map((item, index) => {
								return (
									<View key={index} style={[styles.planList, styles.boxPadding]}>
										<View style={styles.float}>
											<View style={[styles.planTime]} >
												<Text style={styles.listText}>交货时间</Text>
												<View style={{ flexDirection: 'row', }}>
													{this.tCode === 'L' ?
														<View style={styles.timeWrap}>
															<Text style={{
																fontSize: 12 * scale,
																height: 31 * scale,
																lineHeight: 31 * scale
															}}>每月</Text>
															<Text style={{ backgroundColor: '#E4E4E4', height: 1 / PixelRatio.get(), width: 343 * scale, marginTop: 5 * scale }}></Text>
														</View>
														: <TouchableOpacity style={styles.listSelect} onPress={() => this.openDatePicker(index, item)}>
															<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
																<Text style={[styles.timeVlue, { width: 100 * scale }]}>
																	{item.deliveryBeginDate}
																</Text>
																<Text style={[styles.timeVlue, { width: 15 * scale }]}>至</Text>
																<Text style={[styles.timeVlue, { width: 100 * scale, textAlign: 'center' }]}>
																	{item.deliveryEndDate}
																</Text>
															</View>
															<Image style={styles.imgLeft} source={imgObj} />
														</TouchableOpacity>}
													{
														this.tCode === 'L' ? null : <TouchableOpacity onPress={() => { this.removeItem(index) }} style={[styles.addBtn, { marginLeft: 15 * scale, marginTop: 7 * scale }]}>
															<Text style={styles.addBtnText}>删除</Text>
														</TouchableOpacity>
													}
												</View>
											</View>
										</View>
										{
											item.goodsDeliveryPlanList.map((items, index) => {
												return (
													<View style={styles.planCount} key={index} >
														<View style={styles.planRight}>
															<Text style={styles.listText}></Text>
														</View>
														<View style={styles.listSelect}>
															<TextInput
																underlineColorAndroid='transparent'
																keyboardType="numeric"
																style={styles.writeValue}
																defaultValue={items.quantity + ''}
																maxLength={10}
																onChangeText={(text, index) => {
																	items.quantity = text;
																	this._computer(text, index);
																}}
																onEndEditing={() => {
																	this.setState({
																		listData: this.allData
																	})
																}}
															/>
															<Text style={[styles.timeVlue, styles.timeVlueTwo]}>吨</Text>
														</View>
													</View>
												)
											})
										}
									</View>
								)
							})
						}
					</View>
				</ScrollView>
				<DateGapPicker
					isVisible={this.state.openDatePicker}
					date={this.dateObj}
					double={true}
					cb={(newDate) => {
						this.setState({ openDatePicker: false })
						if (!newDate) return;
						let { writeIndex, listData } = this.state;
						listData.map((item, index) => {
							if (index == writeIndex) {
								item.deliveryBeginDate = newDate.startDate || '';
								item.deliveryEndDate = newDate.endDate || '';
							}
						})
						console.log(listData, '----------listData')
						this.setState({ listData })
					}} />
				<Common type="bottom" title="保存" callBack={this._commitCall} />
				{
					status != 'data' ? (<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}><PageStatusIndex status={status} /></View>) : null
				}
			</KeyboardAvoidingView >

		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white
	},
	boxPadding: {
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale
	},
	addBtn: {
		width: 100 * scale,
		height: 27 * scale,
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#89C8FF',
		backgroundColor: '#E2F2FF',
		borderRadius: 2 * scale,
		marginTop: 20 * scale,
		marginBottom: 10 * scale
	},
	addBtnText: {
		color: '#0087FF',
		fontSize: 12 * scale,
		width: 100 * scale,
		lineHeight: 27 * scale,
		textAlign: 'center'
	},
	planCommon: {
		flex: 1,
		marginBottom: 60 * scale,
	},
	planList: {
		paddingBottom: 15 * scale,
		borderBottomWidth: 12 * scale,
		borderStyle: 'solid',
		borderBottomColor: '#F4F4F4',
	},
	planTime: {
		width: 221 * scale
	},
	timeWrap: {
		width: 70 * scale,
		height: 31 * scale,
		marginTop: 12 * scale,
	},
	planCount: {
		width: '100%'
	},
	listText: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		height: 17 * scale,
		lineHeight: 17 * scale,
		marginTop: 17 * scale
	},
	imgLeft: {
		width: 6 * scale,
		height: 11 * scale,
	},
	timeVlue: {
		color: style.color.black,
		fontSize: 14 * scale,
	},
	timeVlueTwo: {
		position: 'absolute',
		right: 0
	},
	listSelect: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		height: 40 * scale
	},
	writeValue: {
		width: '100%',
		color: style.color.black,
		fontSize: 14 * scale
	},
	planRight: {
		flexDirection: 'row',
		justifyContent: 'space-between'
	},
	statusStyle: {
		flex: 1,
		backgroundColor: 'red'
	},
	float: {
		flexDirection: 'row',
		justifyContent: 'space-between',
	},
	amountStyle: {
		color: 'red'
	},
	amountBox: {

	},
	goodNameTitle: {
		width: '100%',
		fontSize: 14 * scale,
		lineHeight: 30 * scale,
		color: style.color.dark,
	},
	infoBody: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
	},
	goodList: {
		flexDirection: 'row',
		marginTop: 5 * scale
	},
	goodListBox: {
		marginTop: 15 * scale
	}
})